#include "../../../shared/infra/etcd.hpp"
#include "../main.pb.h"
#include <brpc/closure_guard.h>
#include <brpc/server.h>
#include <butil/logging.h>
#include <chrono>
#include <gflags/gflags.h>
#include <memory>
#include <thread>

DEFINE_bool(run_mode, false, "程序的运行模式, false-调试 true-发布");
DEFINE_string(log_file, "", "发布模式下，指定日志输出文件");
DEFINE_int32(log_level, 0, "发布模式下，指定日志输出等级");

DEFINE_string(etcd_host, "http://127.0.0.1:2379", "服务注册中心地址");
DEFINE_string(base_service, "/service", "服务监控根目录");
DEFINE_string(instance_name, "/echo/instance", "当前实例名称");
DEFINE_string(access_host, "127.0.0.1:9000", "当前实例的外部访问地址");
DEFINE_int32(listen_port, 9000, "rpc服务器监听端口");

class EchoServiceImpl : public example::EchoService
{
public:
    EchoServiceImpl() {}
    ~EchoServiceImpl() {}
    void Echo(google::protobuf::RpcController* controller, const ::example::EchoRequest* request, 
              ::example::EchoResponse* response, ::google::protobuf::Closure* done)
    {
        brpc::ClosureGuard rpcGuard(done);      // Closure 封装成RAII, 避免忘记调用其run
        std::cout << "收到消息:" << request->message() << "\n";
        std::string respMsg = request->message();
        std::reverse(respMsg.begin(), respMsg.end());
        response->set_message(respMsg);
    }
};

int main(int argc, char* argv[])
{
    google::ParseCommandLineFlags(&argc, &argv, true);
    shared::init_logger(FLAGS_run_mode, FLAGS_log_file, FLAGS_log_level);

    // 1.关闭brpc的默认日志输出
    logging::LoggingSettings settings;
    settings.logging_dest = logging::LoggingDestination::LOG_TO_NONE;
    logging::InitLogging(settings);

    // 2.构建服务器 
    brpc::Server server;
    EchoServiceImpl echoService;

    // 3.向服务器新增echoService服务
    int ret = server.AddService(&echoService, brpc::ServiceOwnership::SERVER_DOESNT_OWN_SERVICE);
    if(ret == -1) {
        std::cout << "添加Rpc服务失败\n";
        return 1;
    }

    // 4.启动服务器
    brpc::ServerOptions options;    // 服务器的配置项
    options.idle_timeout_sec = -1;  // 连接空闲的超时上限(-1表无限空闲)
    options.num_threads = 1;        // io线程数
    ret = server.Start(FLAGS_listen_port, &options);
    if(ret == -1) {
        std::cout << "服务器启动失败\n";
        return 1;
    }

    // 5.注册服务
    shared::infra::RegistrantPtr client = std::make_shared<shared::infra::Registrant>(FLAGS_etcd_host);
    client->registry(FLAGS_base_service + FLAGS_instance_name, FLAGS_access_host);

    server.RunUntilAskedToQuit();   // 休眠等待运行结束

    return 0;
}